package org.example.cardgame.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.cardgame.entity.FlowManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author juanita.ren
 * @Date 2024/11/11 22:04
 * @Version 1.0
 */
@Component
@ServerEndpoint("/websocket/page")
public class PageWebSocket {
    private static Logger logger = LoggerFactory.getLogger(PageWebSocket.class);
    private static Session webSession = null;
    private FlowManager flowManager = FlowManager.getInstance();

    public PageWebSocket() {
    }

    @OnOpen
    public void onOpen(Session session) {
        session.setMaxIdleTimeout(3600000L);
        webSession = session;
        logger.info("PageWebSocket::onOpen web页面连接成功");
    }

    @OnClose
    public void onClose(Session session) {
        webSession = null;
        logger.info("PageWebSocket::onOpen web页面连接断开");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("PageWebSocket::onMessage message:" + message);
        this.dealMessage(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
    }

    public static void sendMessageToWeb(String msg) {
        if (webSession != null && webSession.isOpen()) {
            try {
                synchronized(webSession) {
                    webSession.getBasicRemote().sendText(msg);
                }
            } catch (IOException var4) {
                IOException e = var4;
                logger.error("PageWebSocket::sendMessageToWeb error:", e);
            }
        }

    }

    private void dealMessage(String message) {
        try {
            JSONObject msgJson = JSON.parseObject(message);
            switch (msgJson.getString("type")) {
                case "F_RoundStart":
                    this.flowManager.receiveOperation(FlowManager.WaitOperation.ROUND_START, new HashMap());
                    break;
                case "F_GameRestart":
                    this.flowManager.restart();
            }
        } catch (Exception var6) {
            Exception e = var6;
            logger.error("PageWebSocket::dealMessage error:", e);
        }

    }
}
